﻿using Exam.Filters;
using Exam.infranstuctrue.Dto.Request.Error;
using Exam.Service.Interface;

namespace Exam.MiddleWare
{
    public class ExceptionMiddle
    {

        private readonly RequestDelegate request;

        public ExceptionMiddle(RequestDelegate request)
        {
            this.request = request;
        }
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await request.Invoke(context);
            }
            catch (Exception ex)
            {
                var FileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                System.IO.File.AppendAllText(@"E:\S4\日志\Error\" + FileName, $"IP地址【127.0.0.1】,错误消息【{ex.Message}】,路径【{context.Request.Path}】");
                //_errorService.AddError(new ErrorDto
                //{
                //    ip = "127.0.0.1",
                //    message = ex.Message,
                //    url = context.Request.Path,
                //});

                await context.Response.WriteAsJsonAsync(new
                {
                    code = -500,
                    message = "custom error"
                });
            }
        }
    }
}
